<template>
  <div class="user-editor">
    <table-title
        :title="getTitleText()"
        button-mode="back"
        :back-path="'/admin/' + editType"
        icon="el-icon-s-order">
    </table-title>

    <!-- form -->
    <div class="form-content">
      <el-form ref="form" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="头像">
          <el-upload
              drag
              class="avatar-uploader"
              name="file"
              :action="this.$store.state.api + '/app/order/PictureUpload'"
              :show-file-list="false"
              :on-success="handleSuccess"
              :before-upload="beforeUpload">
            <el-avatar
                v-if="imgUrl"
                :src="imgUrl"
                :size="178"
                shape="square"
                class="avatar">
            </el-avatar>
            <i v-else class="el-icon-plus icon"></i>
          </el-upload>
        </el-form-item>

        <el-row>
          <el-col :span="14">
            <el-form-item label="昵称" prop="userName" key="userName">
              <el-input v-model="form.userName" placeholder="请输入昵称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="姓名" prop="tuserName" key="tuserName">
              <el-input v-model="form.tuserName" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="电话" prop="phone" key="phone">
              <el-input v-model="form.phone" placeholder="请输入电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="身份证号" prop="info" key="info">
              <el-input v-model="form.info" placeholder="请输入身份证号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="住址">
              <el-input v-model="form.address" prop="address" placeholder="请输入住址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="生日">
              <el-date-picker
                  type="date"
                  placeholder="请选择生日"
                  :value-format="'yyyy-MM-dd'"
                  v-model="form.birthday">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col v-if="editType == 'staff'" :span="14">
            <el-form-item label="角色" required>
              <el-select v-model="form.role" placeholder="请选择用户角色">
                <el-option label="居民" value="0"></el-option>
                <el-option label="工作人员" value="1"></el-option>
                <el-option label="管理员" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col v-if="editType == 'staff'" :span="14">
            <el-form-item label="工作区域">
              <el-select v-model="form.workPlace" placeholder="请选择工作区域">
                <el-option
                    v-for="item in workPlaceData"
                    :key="item.typeId"
                    :label="item.placeType"
                    :value="item.typeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="editID != -1">
          <el-col :span="14">
            <el-form-item label="密码">
              <el-button type="danger" icon="el-icon-refresh-right" @click="resetPassword">重置密码</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="action-button">
          <el-col :span="14" align="right">
            <el-button type="danger" icon="el-icon-close" @click="back">取消</el-button>
            <el-button type="primary" icon="el-icon-edit" @click="confirm">
              {{ editID == -1 ? '新增' : '保存' }}
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import TableTitle from "../../../components/TableTitle";

export default {
  name: 'UserEditor',
  components: {TableTitle},
  data() {
    return {
      // 正在编辑的
      editType: '',
      editID: -1,
      // workplace
      workPlaceData: [],

      // 数据
      form: {
        /*"address": "string",
        "birthday": "string",
        "img": "string",
        "info": "string",
        "password": "string",
        "phone": "string",
        "role": "string",
        "tuserName": "string",
        "userId": 0,
        "userName": "string",
        "workPlace": "string"*/
        role: (this.editType == 'resident' ? '0' : '1'),
        workPlace: ""
      },
      // 头像
      imgUrl: '',

      // 校验规则
      formRules: {
        userName: this.$store.state.formRule.userName,
        tuserName: this.$store.state.formRule.name,
        phone: this.$store.state.formRule.phone,
        info: this.$store.state.formRule.idCard,
      },
    };
  },
  computed: {},
  created() {
    // 获取参数
    this.editType = this.$route.params.type;
    this.editID = this.$route.params.id || -1;

    // 编辑信息，获取信息
    if (this.editID != -1) this.getUserData();

    // 获取WorkPlace
    if (this.editType == 'staff') this.getWorkPlace();
  },
  mounted() {

  },
  methods: {
    /**
     * 获取类型标题
     */
    getTitleText() {
      if (this.editType == 'resident' && this.editID == -1) return '添加居民信息';
      if (this.editType == 'resident' && this.editID != -1) return '修改居民信息';

      if (this.editType == 'staff' && this.editID == -1) return '添加员工信息';
      if (this.editType == 'staff' && this.editID != -1) return '修改员工信息';
    },

    /**
     * 获取WorkPlace
     */
    getWorkPlace() {
      this.axios.post(this.$store.state.api + '/work-place/list?pageNum=1&pageSize=500', {})
          .then((response) => {
            if (response.data.code == 200) {
              this.workPlaceData = response.data.data.records;
            }
          })
          .catch((error) => {
            console.log(error);
          });
    },

    /**
     * 获取信息
     */
    getUserData() {
      this.axios.get(this.$store.state.api + '/user/getById?userid=' + this.editID)
          .then((response) => {
            if (response.data.code == 200) {
              const data = response.data.data;
              // 无数据
              if (data == null ||
                  (this.editType == 'resident' && data.role != '0') ||
                  (this.editType == 'staff' && data.role != '1' && data.role != '2')) {
                this.$message({
                  type: 'error',
                  message: '加载数据失败！',
                  onClose: () => {
                    this.$router.replace('/admin/' + this.editType);
                  }
                });
              }
              else {
                this.form = data;
                this.imgUrl = data.img;
              }
            }
          })
          .catch((error) => {
            console.log(error);
          });
    },

    /**
     * 重置密码
     */
    resetPassword() {
      this.$confirm(`此操作将<span style="color: red">重置密码为<strong>身份证后六位</strong></span>, 是否继续?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          })
          .then(() => {
            this.axios.put(this.$store.state.api + '/user/update', [{
              userId: this.form.userId,
              password: this.form.info.substr(12, 6)
            }]).then((response) => {
              if (response.data.code == 200) {
                this.$message({
                  type: response.data.data ? 'success' : 'error',
                  message: response.data.data ? '重置密码成功！' : '重置密码失败！'
                });
              }
            }).catch((error) => {
              console.log(error);
            });
          });
    },

    /**
     * 保存
     */
    confirm() {
      // 新增
      if (this.editID == -1) {
        this.axios.post(this.$store.state.api + '/user/add', {
          birthday: this.form.birthday || '',
          info: this.form.info || '',
          password: this.form.info.substr(12, 6) || '',
          phone: this.form.phone || '',
          role: this.form.role || '',
          tuserName: this.form.tuserName || '',
          userName: this.form.userName || '',
          img: this.form.img || '',
          workPlace: this.form.workPlace + '' || '',
          address: this.form.address || ''
        }).then((response) => {
          if (response.data.data) {
            // 成功
            this.$alert(`默认密码为身份证后六位！`, '添加成功', {
              confirmButtonText: '确定',
              callback: () => {
                this.back();
              }
            });
          }
        }).catch((error) => {
          console.log(error);
        });
      }
      // 更新
      else {
        this.axios.put(this.$store.state.api + '/user/update', [{
          birthday: this.form.birthday || '',
          info: this.form.info || '',
          phone: this.form.phone || '',
          role: this.form.role || '',
          tuserName: this.form.tuserName || '',
          userName: this.form.userName || '',
          img: this.form.img || '',
          workPlace: this.form.workPlace + '' || '',
          address: this.form.address || '',
          userId: this.form.userId
        }]).then((response) => {
          this.$message({
            type: response.data.data ? 'success' : 'error',
            message: response.data.data ? '修改成功！' : '修改失败！',
            duration: 1000,
            onClose: () => {
              this.back();
            }
          });
        }).catch((error) => {
          console.log(error);
        });
      }
    },

    /**
     * 返回
     */
    back() {
      this.$router.replace('/admin/' + this.editType);
    },

    /**
     * 上传成功
     *
     * @param res
     */
    handleSuccess(res) {
      console.log(res);
      this.form.img = res.data;
      this.imgUrl = res.data;
    },

    /**
     * 检测图片大小
     *
     * @param file
     * @return {boolean}
     */
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 <= 3;
      if (!isLt2M) {
        this.$message.error("头像大小不能超过3MB!");
      }
      return isLt2M;
    },
  },
  watch: {
    /**
     * 身份证合法时更新生日
     *
     * @param to
     */
    /*'form.info'(to) {
      if (to.length == 18) {
        this.form.birthday = to.substring(6, 10) + "-" + to.substring(10, 12) + "-" + to.substring(12, 14);
      }
    }*/
  }
};
</script>

<style lang="less" scoped>
@import "../../../assets/less/base.less";

.user-editor {
  color: @fontColor;
  min-height: 100%;
  background: white;
}
</style>

<style lang="less">
.user-editor {

}
</style>